package agents;

import statics.TradingConst;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.AMSService;
import jade.domain.FIPAAgentManagement.AMSAgentDescription;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.lang.acl.ACLMessage;

public class TickAgent extends Agent {
	private int TickCount =0;
	private AMSAgentDescription[] agents;
	public static final int N_TICKS_TO_SYNC = 2;//all agent will wait for at least this number of tick before action
	
	protected void setup() 
	{
		addBehaviour(new TickerBehaviour(this,TradingConst.TickListenerAgentRefreshingMS) {

			@Override
			protected void onTick() {
				try 
				 {
					 SearchConstraints c = new SearchConstraints();
					 c.setMaxResults (new Long(-1));
				     agents = AMSService.search(myAgent, new AMSAgentDescription (), c );
				 }
				 catch (Exception e) {
					 System.out.println( "Problem searching AMS: " + e );
				     e.printStackTrace();
				 }
			}
		
		});
		 
		 
		addBehaviour(new TickerBehaviour(this,TradingConst.Tick_TO_MS) {
			
			@Override
			protected void onTick() {
				// TODO Auto-generated method stub
				if(agents != null)
				{
					ACLMessage tickInform = new ACLMessage(ACLMessage.INFORM);
					tickInform.setConversationId("tick");
					tickInform.setContent(String.valueOf(++TickCount));
					for (int i = 0; i < agents.length; ++i) {
						tickInform.addReceiver(agents[i].getName());
					}
					//Send message out
					myAgent.send(tickInform);
				}
			}
		});
	}
}
